package com.lzb.musicplayer.view;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class VerticalSeekBar extends androidx.appcompat.widget.AppCompatSeekBar {

    public VerticalSeekBar(Context context) {
        super(context);
    }

    public VerticalSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public VerticalSeekBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        canvas.save();
        canvas.rotate(-90);
        canvas.translate(-getHeight(), 0);
        super.onDraw(canvas);
        canvas.restore(); // 增加恢复画布


    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) return false;

        // 坐标转换：将物理坐标系转换为旋转后的逻辑坐标系
        float x = event.getX();
        float y = event.getY();

        // 旋转坐标系（反向旋转90度）
        float rotatedX = getHeight() - y;
        float rotatedY = x;

        // 计算可用高度（考虑padding）
        int availableHeight = getHeight() - getPaddingTop() - getPaddingBottom();
        float progressPos = Math.max(0, Math.min(rotatedX - getPaddingTop(), availableHeight));

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                int newProgress = (int) (getMax() * progressPos / availableHeight);
                setProgress(newProgress);
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(true); // 防止滚动冲突
                }
                break;
            default:
                break;
        }
        return true;
    }
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(h, w, oldw, oldh);
    }
    @Override
    public synchronized void setProgress(int progress) {
        super.setProgress(progress);
        onSizeChanged(getWidth(), getHeight(), 0, 0); // 强制重绘

    }
    private int dpToPx(Context context, float dp) {
        return (int) (dp * context.getResources().getDisplayMetrics().density);
    }
    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
        // 更新drawable状态（用于点击效果）
        if (getProgressDrawable() != null) {
            getProgressDrawable().setState(getDrawableState());
        }
        if (getThumb() != null) {
            getThumb().setState(getDrawableState());
            invalidate();
        }
    }
}